<template>
  <el-dialog append-to-body class="common_dialog_in" custom-class="reset-dialog-width" :visible.sync="visible" title="选择商品" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-table :border="true" :data="orderGoods">
      <el-table-column label="商品ID" width="120" align="center" prop="goodsId"></el-table-column>
      <el-table-column label="商品名称" align="center" prop="title"></el-table-column>
      <el-table-column label="首图" align="center" prop="image">
        <template slot-scope="scope">
          <ImagePreview width="100px" height="100px" noneType="暂无图片" :src="scope.row.image" fit="cover"></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" prop="images">
        <template slot-scope="scope">
          <ImagePreview width="100px" height="100px" noneType="暂无图片" :src="scope.row.images" fit="cover"></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price"></el-table-column>
      <el-table-column label="商品审核状态" align="center">
        <template slot-scope="scope">
          <div class="content_text">
            <dict-tag class="tag" :options="dict.type.jieke_ordersales_status" :value="scope.row.orderSales ? scope.row.orderSales.status : '无'" />
            <div class="content">{{scope.row.orderSales && scope.row.orderSales.status == 90 ? '('+scope.row.orderSales.shenContent+')':''}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="toggleSelectHandle(scope.row)" :style="actionStyle(scope.row)" v-if="!scope.row.orderSales || (scope.row.orderSales.status != -1 && scope.row.orderSales.status != 40 && scope.row.orderSales.status != 90)">
            {{actionText(scope.row)}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template slot="footer">
      <div class="flex_item">
        <div class="text" v-if="type == 'refund'">退款金额：{{refundPrice}}</div>
        <el-button :loading="confirmLoading" type="primary" @click="formSubmitHandle()">确 定</el-button>
        <!-- <el-button :loading="finishLoading" type="success" @click="finish">售后完成</el-button> -->
        <el-button @click="visible = false;value=[]">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { orderReback, orderRefund, orderSave, getOrder } from "@/api/order/order";
export default {
  dicts: ['jieke_ordersales_status'],
  data() {
    return {
      visible: false, //弹窗是否显示
      confirmLoading: false, //确认按钮loading
      id: '', //上一个页面传入的订单id
      row: {}, //订单详细信息
      value: [], //选中的value值
      type: '', //弹窗的类型 退款refund 返洗reback
      refundPrice: 0, //退款金额
      finishLoading: false, //售后完成的按钮
      orderGoodsIds: [], //需要退款的商品id
      orderGoods: [],//商品列表
    }
  },
  components: {
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.value = []
        this.confirmLoading = false
        this.refundPrice = 0
        this.orderGoodsIds = []
        this.orderGoods = []
        this.id ? this.getInfo() : ''
      })
    },
    // 获取订单id的详情
    getInfo() {
      const id = this.id
      getOrder(id).then(response => {
        this.row = response.data
        // let list = []
        // response.data.orderGoods && response.data.orderGoods.map((item) => {
        //   if (item.orderSales && (item.orderSales.status == 10 || item.orderSales.status == 20)) {
        //     list.push(item)
        //   }
        // })
        this.orderGoods = response.data.orderGoods
      });
    },
    actionStyle(row) {
      let color = "#666";
      if (this.value) {

        if (this.value instanceof Array) {
          this.value.forEach(item => {
            if (item.id == row.id) {
              color = "#409EFF";
            }
          });
        }
        else {
          if (this.value.id == row.id) {
            color = "#409EFF";
          }
        }
      }
      return {
        color
      }
    },
    actionText(row) {
      let text = "未选择";
      if (this.value) {
        if (this.value instanceof Array) {
          this.value.forEach(item => {
            if (item.id == row.id) {
              text = "已选择";
            }
          });
        }
        else {
          if (this.value.id == row.id) {
            text = "已选择";
          }
        }
      }
      return text
    },
    toggleSelectHandle(row) {
      if (this.value instanceof Array) {
        const index = this.value.findIndex((r) => r.id === row.id);
        if (index > -1) {
          this.value.splice(index, 1);
          this.refundPrice = ((this.refundPrice * 100) - (row.price * 100)) / 100
        } else {
          this.value.push({ ...row });
          this.refundPrice = ((this.refundPrice * 100) + (row.price * 100)) / 100
        }
      } else {
        if (row.id === this.value?.id) {
          this.value = {};
          this.refundPrice = 0
        } else {
          this.value = { ...row };
          this.refundPrice = row.price
        }
      }
      //  console.log(this.value)
    },
    // 点击售后完成
    finish() {
      if (this.orderGoods.length) {
        this.$modal.msgError("当前订单还存在未审核的商品");
        return
      }
      let data = {
        id: this.row.id,
        status: 52
      }
      this.finishLoading = true
      orderSave(data).then((res) => {
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }
        this.finishLoading = false
        this.$modal.msgSuccess("操作成功");
        this.visible = false
        this.$emit('refreshDataList')
      }).catch(() => {
        this.finishLoading = false
      })
    },
    // 表单提交
    formSubmitHandle: debounce(function () {
      if (!this.value.length) {
        this.$modal.msgError("请选择商品");
        return
      }
      // console.log(this.value)
      this.value.map((item) => {
        this.orderGoodsIds.push(item.id)
      })
      // refund 请求订单退款接口
      if (this.type == 'refund') {
        this.confirmLoading = true
        this.$confirm('是否确认为选中商品进行退款？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let datas = {
            number: this.row.number,
            orderId: this.row.id,
            refundAmount: this.refundPrice,
            orderGoodsIds: encodeURI(this.orderGoodsIds)
          }
          orderRefund(datas).then((res) => {
            if (res.code !== 200) {
              return this.$message.error(res.msg)
            }
            this.$modal.msgSuccess("操作成功");
            // this.visible = false
            this.confirmLoading = false
            this.value = []
            this.orderGoodsIds =[]
            this.refundPrice = 0
            this.getInfo()
            // this.$emit('refreshDataList')
          }).catch(() => { this.confirmLoading = false })
        }).catch(() => { this.confirmLoading = false })
      }
    }, 1000, { 'leading': true, 'trailing': false }),

  }
}
</script>
<style lang="scss" scoped>
.common_dialog_in {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  ::v-deep.el-dialog {
    margin: 0 auto !important;
    max-height: 1000px;

    .el-dialog__body {
      overflow: hidden;
      overflow-y: auto;
      max-height: 800px;
    }
  }
}
.flex_item {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .text {
    margin-right: 30px;
    color: #f56c6c;
  }
}
</style>
